//
//  UserAccount.swift
//  新浪微博
//
//  Created by macbook on 16/3/11.
//  Copyright © 2016年 buWangChuXing. All rights reserved.


//主要是字典转模型，保存数据，对外提供数据

import UIKit


private let userInfoKey = "cn.itcast.account"

class UserAccount: NSObject {

    //接口获取授权后的access_token。用户访问接口权限标识
    var access_token: String?
    
    //access_token 的生命周期，单位是秒数
    var expires_in : NSTimeInterval = 0
    
    //当前授权ID
    var uid : String?
    
    //当前用户登录名称
    var name : String?
    
    //当前用户头像
    var avatar_large : String?
    
    //实现过滤不存在key  的方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String){ }
    
    override var description: String {
    
        //只读属性
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        
        let accountDict = dictionaryWithValuesForKeys(keys)
        
        return accountDict.description
    
    
    }
}


//保存数据，获取数据

extension UserAccount {

    //保存用户信息
    func saveUserInfo(dict : [String : AnyObject]){
    
        //给当前对象KVC设置初始值 未登录状态 --> 登录状态
        
        self.setValuesForKeysWithDictionary(dict)
        
        //保存当前对象所有属性 用字典的形式
        let userDefaults = NSUserDefaults.standardUserDefaults()
        //获取当前对象的字典信息
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        //将用户信息保存到沙河
        userDefaults.setObject(accountDict, forKey: userInfoKey)
        //同步沙盒
        userDefaults.synchronize()
        
        //测试打印
        print(NSHomeDirectory())
    
    }


    //提供对外访问方式
    
    func loadUserInfo(){
    
        //从偏好设置中获取字典信息
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else{
        
        return
        
        }
    //将字典信息转换模型数据
        self.setValuesForKeysWithDictionary(dict)
        print(self)
    
    }
    

}












